# encoding:utf8
"""
@File        : mryx.py
@Time        : 2019/6/25 15:41
@Author      : zhaoy
@Email       : zhaoyao@shandiangou.cc
@Description :  每日优鲜
"""

import json

import scrapy

from .mryx_cateid import categories


class MeiRiYouXuan(scrapy.Spider):
    name = 'mryx'
    allowed_domains = ['missfresh.cn']
    custom_settings = {
        'DEFAULT_REQUEST_HEADERS': {
            'Host': "as-vip.missfresh.cn",
            'Content-Type': "application/json",
            'x-region':
                '{"station_code":"","address_code":511602,"delivery_type":0,"chrome_type":2,"bigWarehouse":"MRYXSZ"}',
            'Connection': "keep-alive",
            'Accept': "*/*",
            'User-Agent': "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 "
            "(KHTML, like Gecko) Mobile/14G60 MicroMessenger/7.0.3(0x17000321) NetType/WIFI Language/zh_CN",
            'Accept-Language': "zh-cn",
        },
        'IMAGES_STORE': 'G:/spiders_data/images/mrxs/',
        'ITEM_PIPELINES': {
            'baiguoyuan.pipelines.GoodsImagesPipeline': 1,
            'baiguoyuan.pipelines.CommomPipelines': 321
        },
    }

    def start_requests(self):
        for cat in categories:
            catid = cat.get('internalId')
            # name = cat.get('subTitle')
            url = ('https://as-vip.missfresh.cn/as/home/category/classifyProductInfo?env=weixin_app&'
                   'platform=weixin_app&device_id=2c807878-0bcf-90f7-8c7c-3be970b7f2e5&version=9.1.0.16&'
                   'model=iPhone%206s%20Plus%3CiPhone8%2C2%3E&deliveryType=0&fromSource=zhuanqianzhongxin')

            payload = {
                "common": {
                    "env": "weixin_app",
                    "platform": "weixin_app",
                    "device_id": "2c807878-0bcf-90f7-8c7c-3be970b7f2e5",
                    "deviceId": "2c807878-0bcf-90f7-8c7c-3be970b7f2e5",
                    "sourceDeviceId": "2c807878-0bcf-90f7-8c7c-3be970b7f2e5",
                    "version": "9.1.0.16",
                    "model": "iPhone%206s%20Plus%3CiPhone8%2C2%3E",
                    "screenHeight": 736,
                    "screenWidth": 414,
                    "currentLat": 30.78306,
                    "currentLng": 106.69476,
                    "addressCode": 511602,
                    "stationCode": "",
                    "deliveryType": 0,
                    "chromeType": 2,
                    "fromSource": "zhuanqianzhongxin"
                },
                "param": {
                    "categoryCode": catid,
                    "categoryVersion": "",
                    "lastProductIndex": 0,
                    "secondGroupId": ""
                }
            }
            yield scrapy.Request(url, method='POST', body=json.dumps(payload))

    def parse(self, response):
        data = response.text
        data = json.loads(data)
        image_urls = []
        image_header = {
            'Accept': "image/*;q=0.8",
            'Accept-Language': "zh-cn",
            'Connection': "keep-alive",
            'Accept-Encoding': "gzip, deflate",
            'User-Agent': 'NewMissFresh/9.1.1 (iPhone; iOS 10.3.3; Scale/3.00)'
        }
        try:
            dt = data.get('data').get('cellList')
        except AttributeError:
            dt = None
        if dt:
            print(dt)
            image_urls = [(item.get('normalProducts').get('image'), item.get('secondGroupName')) for item in dt
                          if item.get('normalProducts')]
        data.update({'data_collection': 'mryx_goods', 'data_from': 'data.cellList', 'image_urls': image_urls,
                     'image_header': image_header})
        yield data
